package com.imooc.service.impl;

import com.imooc.mapper.OrderItemsMapper;
import com.imooc.mapper.OrdersMapper;
import com.imooc.pojo.*;
import com.imooc.pojo.bo.SubmitOrderBO;
import com.imooc.service.AddressService;
import com.imooc.service.ItemService;
import com.imooc.service.OrderService;
import imooc.enums.YesOrNo;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 订单service
 * */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ItemService itemService;

    /**
     * 创建订单
     * */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {Exception.class})
    @Override
    public void createOrder(SubmitOrderBO submitOrderBO) throws Exception {
        String userId = submitOrderBO.getUserId();
        String addressId = submitOrderBO.getAddressId();
        String itemSpecIds = submitOrderBO.getItemSpecIds();
        Integer payMethod = submitOrderBO.getPayMethod();
        String leftMsg = submitOrderBO.getLeftMsg();
        // 包邮费用设置为0
        Integer postAmount = 0;

        String orderId = sid.nextShort();

        UserAddress userAddress = addressService.queryUserAddress(userId, addressId);

        // 1. 新订单数据保存
        Orders newOrder = new Orders();
        newOrder.setId(orderId);
        newOrder.setUserId(userId);
        newOrder.setReceiverName(userAddress.getReceiver());
        newOrder.setReceiverMobile(userAddress.getMobile());
        StringBuilder address = new StringBuilder();
        address.append(userAddress.getProvince() + " ");
        address.append(userAddress.getCity() + " ");
        address.append(userAddress.getDistrict() + " ");
        address.append(userAddress.getDetail());
        newOrder.setReceiverAddress(address.toString());

//        newOrder.setTotalAmount();
//        newOrder.setRealPayAmount();
        String itemSpecIdArr[] = itemSpecIds.split(",");
        // 商品原价累计
        Integer totalAmount = 0;
        // 优惠后的实际支付价格累计
        Integer realPayAmount = 0;
        ItemsSpec itemsSpec = null;
        for (String itemSpecId : itemSpecIdArr) {
            // 1. 根据规格ID，查询规格信息，获取价格
            int buyCounts = 1;
            itemsSpec = itemService.queryItemSpecById(itemSpecId);
            if (null == itemsSpec) {
                throw new Exception("商品不存在");
            }
            // TODO 整合redis后，商品购买的数量重新从redis的购物车中获取
            totalAmount += itemsSpec.getPriceNormal() * buyCounts;
            realPayAmount += itemsSpec.getPriceDiscount() * buyCounts;

            // 2. 根据商品ID，获取商品
            String itemId = itemsSpec.getItemId();
            Items items = itemService.queryItemById(itemId);
            String url =  itemService.queryItemMainImgById(itemId);

            // 3. 保存子订单数据到数据库
            String subOrderId = sid.nextShort();
            OrderItems subOrderItem = new OrderItems();
            subOrderItem.setId(subOrderId);
            subOrderItem.setOrderId(orderId);
            subOrderItem.setItemId(itemId);
            subOrderItem.setItemName(items.getItemName());
            subOrderItem.setItemImg(url);
            subOrderItem.setBuyCounts(buyCounts);
            subOrderItem.setItemSpecId(itemSpecId);
            subOrderItem.setItemSpecName(itemsSpec.getName());
            subOrderItem.setPrice(itemsSpec.getPriceDiscount());

            orderItemsMapper.insert(subOrderItem);
        }

        newOrder.setTotalAmount(totalAmount);
        newOrder.setRealPayAmount(realPayAmount);

        // 邮费
        newOrder.setPostAmount(postAmount);

        // 支付方式
        newOrder.setPayMethod(payMethod);
        // 用户留言
        newOrder.setLeftMsg(leftMsg);
        // 是否被评价过
        newOrder.setIsComment(YesOrNo.NO.type);
        // 是否被删除
        newOrder.setIsDelete(YesOrNo.NO.type);

        newOrder.setCreatedTime(new Date());
        newOrder.setUpdatedTime(new Date());

        // 2. 循环根据itemSpecIds 保存商品订单数据表
        // 3. 保存订单状态表
        ordersMapper.insert(newOrder);
        

    }
}
